package com.ilovepostcard;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;

import com.ilovepostcard.controller.OffLineManager;
import com.ilovepostcard.controller.PostcardController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.data.OffLinePostcard;
import com.ilovepostcard.data.Postcard;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.NetWorkUtil;
import com.ilovepostcard.utils.Utils;
import com.ilovepostcard.view.MyEditText;
import com.mobclick.android.MobclickAgent;

public class PreviewActivity extends BaseActivity implements OnClickListener,OnCheckedChangeListener{

	private final static int DLG_ID_PROCESSING = 3;
	
	Button confirm;
	GridView tag;
	ImageView mReturn;
	ImageView mpcImage;
	MyEditText mComment;
	CheckBox mShare;
	CheckBox mLocation;
	TextView mdate;
	ArrayList<String> options;
	TextView mPCLocation;
	View pcView;
	static HashMap<Integer,String> mTagsMap;
	
	static 
	{
		mTagsMap =  new HashMap<Integer,String>();
		mTagsMap.put(new Integer(0), Constants.TAG_PEOPLE);
		mTagsMap.put(new Integer(1), Constants.TAG_VIEW);
		mTagsMap.put(new Integer(2), Constants.TAG_IDEA);
		mTagsMap.put(new Integer(3), Constants.TAG_FOOD);
		mTagsMap.put(new Integer(4), Constants.TAG_ART);
		mTagsMap.put(new Integer(5), Constants.TAG_PHOTOGRAPH);
		mTagsMap.put(new Integer(6), Constants.TAG_CUTE);
		mTagsMap.put(new Integer(7), Constants.TAG_PEOPLE);
	}
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_preview);
		init();
		
		int page = OffLineManager.getInstance().getResumePage(this);
		if(page == 3)
		{
			OffLinePostcard offline = OffLineManager.getInstance().getCurrentBackupPC();
			String share = offline.get(OffLinePostcard.TAG_CANBEFOUND);
			boolean shareRes = false;
			
			if(share!= null && share.equals("yes"))
				shareRes = true;
			mShare.setChecked(shareRes);
			
			String location = offline.get(OffLinePostcard.TAG_CANBEFOUND);
			boolean locationRes = false;
			
			if(location!= null && location.equals("yes"))
				locationRes = true;
			mLocation.setChecked(locationRes);
			
			
			OffLineManager.getInstance().clearResumeInfo(this);
		}
		
		MobclickAgent.onEvent(this, Constants.COUNT_CREAT_REVIEW);
			
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		
	}
	
	
	protected Dialog onCreateDialog( int id )
    {
        if( id == DLG_ID_PROCESSING )
        {
            ProgressDialog processDlg = new ProgressDialog( this );
            processDlg.setMessage(getResources().getString(R.string.loading));
            processDlg.setIndeterminate( true );
            processDlg.setCancelable( false );
			return processDlg;
        }       

        return super.onCreateDialog( id );
	}	
	
	private void init()
	{
	
		pcView = findViewById(R.id.pc_view);
		pcView.setDrawingCacheEnabled(true);  
		options = new ArrayList<String>();
		tag = (GridView)findViewById(R.id.pc_preview_tag);
		tag.setAdapter(new TagAdpater());
		
		confirm = (Button)findViewById(R.id.pc_preview_finish);
		confirm.setOnClickListener(this);

		mReturn = (ImageView)findViewById(R.id.title_return);
		mReturn.setOnClickListener(this);
		
		mdate = (TextView)findViewById(R.id.preview_date);
		mpcImage = (ImageView)findViewById(R.id.pc_preview);
		mComment = (MyEditText)findViewById(R.id.pc_preview_input);
		
		mShare = (CheckBox)findViewById(R.id.pc_preview_share);
		mLocation = (CheckBox)findViewById(R.id.pc_preview_share_location);
		
		mLocation.setOnCheckedChangeListener(this);
		mShare.setOnCheckedChangeListener(this);
		mPCLocation = (TextView)findViewById(R.id.preview_address);
		
		tag.setOnItemClickListener(new OnItemClickListener()
		{

			@SuppressWarnings("rawtypes")
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				TextView item = (TextView)arg1.findViewById(R.id.share_tag);
				
				
				if(options.size()>=3 && !item.isSelected())
				{
					 /*new AlertDialog.Builder(PreviewActivity.this).
				     setMessage(PreviewActivity.this.getResources().getString(R.string.preview_selectOptions_tip))
				     .setPositiveButton(R.string.know,  new DialogInterface.OnClickListener()
				     {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}


				     })
				     .create()
				     .show();*/
					Utils.showConfirmDialogSingle(PreviewActivity.this, PreviewActivity.this.getString(R.string.preview_selectOptions_tip), new Runnable()
					{

						@Override
						public void run() {
							// TODO Auto-generated method stub
							
						}
						
					});
					return;
				}
				
				
				
				item.setSelected(!item.isSelected());
				
				String newTag = mTagsMap.get(new Integer(arg2));
				if(item.isSelected())
				{
					options.add(newTag);
				}
				else
				{
					options.remove(newTag);
				}
				
				OffLinePostcard pc = OffLineManager.getInstance().getCurrentBackupPC();
				if(pc != null)
				{
					if(options.size()>0)
					{
						options.trimToSize();
						String[] tags = new String[options.size()];
						
						tags =options.toArray(tags);
						pc.save(OffLinePostcard.TAG_TAGS, getTags(tags));
					}

					OffLineManager.getInstance().updateOffLinePc(PreviewActivity.this, pc.getName(), 3);
				}
			}
			
		});
		
	}
	
	private void syncInfo()
	{
		//String message = OffLineManager.getInstance().getCurrentBackupPC().get(OffLinePostcard.TAG_COMMENT);
		//if(currentPc.comment == null)
		Postcard currentPc =  PostcardController.getInstance().getCurrentPostCard();
		Bitmap  image= currentPc.getTmpEditPC();
		//currentPc.comment  =  message;//this.getResources().getString(R.string.postcard_defaultcomment);
		
		if(currentPc.comment == null || currentPc.comment.length() == 0)
			currentPc.comment  =  this.getResources().getString(R.string.postcard_defaultcomment);
		mComment.setText(currentPc.comment);
		
		mdate.setText(currentPc.createTime);
		mpcImage.setBackgroundDrawable(new BitmapDrawable(image));
		if(currentPc.location!= null)
			mPCLocation.setText(currentPc.location);
	}
	
	public void onResume()
	{
		super.onResume();
		syncInfo();
		MobclickAgent.onResume(this); 
	}

	protected void onPause()
	{
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	
	class TagAdpater extends BaseAdapter
	{

		String[] tags = getResources().getStringArray(R.array.tags);
		@Override
		public int getCount() {
			
			return tags.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return tags[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			TextView title= null;
			if(convertView == null)
			{
				convertView= LayoutInflater.from(PreviewActivity.this).inflate(R.layout.share_tag_item, null);
				AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,AbsListView.LayoutParams.WRAP_CONTENT);
				params.height= 60;
				convertView.setLayoutParams(params);
			}
			
			title = (TextView)convertView.findViewById(R.id.share_tag);
			title.setText(tags[position]);
			return convertView;
		}
		
	}


	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.pc_preview_finish)
		{
			
			if (!NetWorkUtil.isNetworkAvailable(this)) {
				Toast.makeText(this,R.string.savetoOffline_tip, Toast.LENGTH_SHORT).show();
				Intent nextPage = new Intent(PreviewActivity.this,ShareNoNetworkActivity.class);
				startActivity(nextPage);
	        }
			else
			{
				if(OffLineManager.getInstance().getCurrentBackupPC() != null)
				{
					OffLineManager.getInstance().delete(OffLineManager.getInstance().getCurrentBackupPC().getName());
					
				}
				
				
				final Postcard pc = PostcardController.getInstance().getCurrentPostCard();
				pc.showLocationFlag = mLocation.isChecked() ? 1 : 0;
				pc.canBeFoundFlag = mShare.isChecked() ? 1:0;
				Bitmap bitmap = pcView.getDrawingCache();
				
				Canvas convas = new Canvas(bitmap);
				convas.drawColor(Color.WHITE);
				
				Handler handle = new Handler();
				handle.post(new Runnable()
				{

					@Override
					public void run() {
						final Postcard pc = PostcardController.getInstance().getCurrentPostCard();
						/*if(pc.pcView!= null && !pc.pcView.isRecycled())
							pc.pcView.recycle();*/
						Bitmap postcard = Bitmap.createBitmap(pcView.getWidth(), pcView.getHeight(),Bitmap.Config.ARGB_8888);
						Canvas canvas = new Canvas(postcard);
						canvas.drawColor(Color.WHITE);
						Drawable bgDrawable =pcView.getBackground();
						if (bgDrawable!=null) 
						     bgDrawable.draw(canvas);
						pcView.draw(canvas);
						//pc.pcView=postcard;
						pc.setTmpEditPCView(postcard);
						
					}
					
				});
				if(options.size()>0)
				{
					options.trimToSize();
					
					String[] tags = new String[options.size()];
					
					tags =options.toArray(tags);
					pc.tags = tags;
				}
				
				final StringBuffer tagslist = new StringBuffer();
				
				
				if(pc.tags != null)
				{
					for(int i=0;i<pc.tags.length;i++)
					{
						if(i==0) 
							tagslist.append(pc.tags[i]);
						else
							tagslist.append(","+pc.tags[i]);
							
					}
						
				}
				uploadPostCard(pc,tagslist.toString());
				OffLineManager.getInstance().finishCurrentbackupPC(this);
				
			}
			
			
		}
		else if(v.getId() == R.id.title_return)
		{
			finish();
		}
		
	}
	
	private void spawnPostcardPreviewImage(View view,String path) {
		Utils.ensureDirExist();
		Bitmap postcard = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(postcard);
		canvas.drawColor(Color.WHITE);
		Drawable bgDrawable =view.getBackground();
		if (bgDrawable!=null) 
		     bgDrawable.draw(canvas);
		view.draw(canvas);
		
		try {
			
			FileOutputStream out = new FileOutputStream(new File(path));
			if (postcard.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
				out.flush();
				out.close();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private Bitmap getPreviewImage(View view) {
		Utils.ensureDirExist();
		Bitmap postcard = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(postcard);
		Drawable bgDrawable =view.getBackground();
		if (bgDrawable!=null) 
		     bgDrawable.draw(canvas);

		return postcard;
	}
	
	private String getTags(String[] list)
	{
		final StringBuffer tagslist = new StringBuffer();
	
	
		if(list != null)
		{
			for(int i=0;i<list.length;i++)
			{
				if(i==0) 
					tagslist.append(list[i]);
				else
					tagslist.append(","+list[i]);
					
			}
			
			return tagslist.toString();
		}
		return null;
		
	}
	private void uploadPostCard(Postcard pc , String tags)
	{
		AsyncUploadTask  tasl = new AsyncUploadTask();
		tasl.setActivity(this);
		tasl.execute(pc, tags);
	}
	
	
	private class AsyncUploadTask extends AsyncTask<Object, Object, Object>
	{
		
		PreviewActivity 	activity;
		public AsyncUploadTask()
		{
			
		}
		
		public void setActivity(PreviewActivity activity)
		{
			this.activity = activity;
		}
		
		@Override
		protected void onPreExecute()
		{
			if (activity != null)
			{
				activity.showDialog(DLG_ID_PROCESSING);
			}
		}

		@Override
		protected Object doInBackground(Object... params) {

			PostcardResult result ;
			Postcard pc =  (Postcard)params[0];
			Bitmap pcBitmap = pc.getTmpEditPC();
			String tags = (String)params[1];
			IServer server = ServerFactory.getServer();
			String folder = Constants.APP_DIR;
			File dataRoot = new File(folder);
			if(!dataRoot.exists())
				dataRoot.mkdir();

			String file = folder+"tmp.jpg";
			String updateKey = server.getUploadSKey().getUploadSKey();
			try {
				Utils.saveBitmap(pcBitmap, file);
			} catch (IOException e) {
				e.printStackTrace();
			}
			File source = new File(file);
			server.uploadFile(IServer.FILE_TYPE_POSTCARD, "tmp.jpg", updateKey, pc.user.UserID, 0, 0, pcBitmap.getWidth(), pcBitmap.getHeight(), 0, source);
			result = server.createPostcard(pc.user.UserID, pc.location == null ? "" : pc.location,pc.comment == null ?"":pc.comment, "", true, pc.latitude,pc.longitude, updateKey, pc.canBeFoundFlag, pc.showLocationFlag,tags==null?"":tags);
			source.delete();
			Postcard currentPc =  PostcardController.getInstance().getCurrentPostCard();
			currentPc.id  = result.getResult();
			
			return result;
		}
		@Override
		protected void onPostExecute(Object result)
		{
			PostcardResult res = (PostcardResult)result;
			if (activity != null)
			{
				activity.dismissDialog(DLG_ID_PROCESSING);
				activity = null;
			}
			
			if(res.isSuccess())
			{
				Toast.makeText(PreviewActivity.this, R.string.upload_success, Toast.LENGTH_SHORT).show();
				Intent nextPage = new Intent(PreviewActivity.this,SharekActivity.class);
				nextPage.putExtra("pid", (long)res.getResult());
				startActivity(nextPage);
			}
			else
			{
				Toast.makeText(PreviewActivity.this, PreviewActivity.this.getResources().getString(R.string.upload_failed)+", error:"+res != null ? res.getErrorMsg(PreviewActivity.this) : "unknow", Toast.LENGTH_LONG).show();
			}
			
		}
		
	}


	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		
		if(buttonView.getId() == R.id.pc_preview_share)
		{
			OffLinePostcard pc = OffLineManager.getInstance().getCurrentBackupPC();
			if(pc!= null)
			{
				pc.save(OffLinePostcard.TAG_CANBEFOUND, isChecked? "no" : "yes");
			}
		}
		else if(R.id.pc_preview_share_location == buttonView.getId())
		{
			OffLinePostcard pc = OffLineManager.getInstance().getCurrentBackupPC();
			if(pc!= null)
			{
				pc.save(OffLinePostcard.TAG_SHOWLOCATION, isChecked? "no" : "yes");
			}
		}
		
		if(OffLineManager.getInstance().getCurrentBackupPC()!= null)
			OffLineManager.getInstance().updateOffLinePc(PreviewActivity.this, OffLineManager.getInstance().getCurrentBackupPC().getName(), 3);
	}
	
		 

}
